package de.webalpha.parking.controller;

import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import de.webalpha.parking.model.ParkingLot;

//The @Stateful annotation eliminates the need for manual transaction demarcation
@Stateful
//The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an
//EL name
//Read more about the @Model stereotype in this FAQ:
//http://sfwk.org/Documentation/WhatIsThePurposeOfTheModelAnnotation
@Model
public class ParkingLotController {

	@Inject
	private Logger log;

	@Inject
	private EntityManager em;

	@Inject
	private Event<ParkingLot> parkingLotEventSrc;

	private ParkingLot newParkingLot;

	@Produces
	@Named
	public ParkingLot getNewParkingLot() {
		return newParkingLot;
	}

	public void register() throws Exception {
		log.info("Registering new parking lot with id: " + newParkingLot.getId());
		em.persist(newParkingLot);
		parkingLotEventSrc.fire(newParkingLot);
		initNewParkingLot();
	}

	@PostConstruct
	public void initNewParkingLot() {
		newParkingLot = new ParkingLot();
	}
}
